<?php
namespace Application\Api\Controller;

class Withdraw extends Base
{

    private function getService()
    {
        return $this->get(SERVICE_WITHDRAW);
    }

    /*提现实际到账*/
    private function calculate($userId, $amount)
    {
        return bcadd($amount, 0, 2);
    }

    /*
        /Api/Withdraw/calculate
    */
    public function calculateAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'device') || notSetOrEmpty($data, 'token') || notSetOrEmpty($data, 'amount')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $device = $data['device'];
        $amount = (int)$data['amount'];
        if($amount <= 0){
            $this->sendFail('FAIL', '提现金额错误');
            return false;
        }
        /*判断token*/
        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $device);
        if(!$userId){
            $this->sendFail('FAIL', '请登录后再操作', __LINE__);
            return false;
        }
        $realAmount = $this->calculate($userId, $amount);
        $send = [
            'real_amount' => $realAmount
        ];
        $this->sendSuccess($send);
    }

    /*
        /Api/Withdraw/add
    */
    public function addAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'device') || notSetOrEmpty($data, 'token') || notSetOrEmpty($data, 'amount') || notSetOrEmpty($data, 'id')){
            $this->sendFail('PARAMETER_ERROR');
            return false;
        }
        $device = $data['device'];
        $amount = (int)$data['amount'];
        $id = (int)$data['id'];
        if($amount <= 0){
            $this->sendFail('FAIL', '提现金额错误');
            return false;
        }
        if($id <= 0){
            $this->sendFail('FAIL', '银行卡错误');
            return false;
        }
        /*判断token*/
        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $device);
        if(!$userId){
            $this->sendFail('TOKEN_ERROR', '', __LINE__);
            return false;
        }
        /*银行卡是否存在*/
        $userBank = $this->get(SERVICE_USERBANK)->one($id);
        if(!$userBank){
            $this->sendFail('FAIL', '银行卡错误');
            return false;
        }
        /*锁*/
        $serviceLock = $this->get(SERVICE_LOCK);
        $name = "user_withdraw_{$userId}";
        if($serviceLock->isFirst($name, WITHDRAW_SPAN_TIME)){
            /*检查余额*/
            $serviceUserAccount = $this->get(SERVICE_USERACCOUNT);
            $userAccount = $serviceUserAccount->one($userId);
            if(!$userAccount || $amount > $userAccount->dry_balance){
                $serviceLock->removeLock($name);
                $this->sendFail('FAIL', '余额不足');
                return false;
            }
            /*实际到账*/
            $realAmount = $this->calculate($userId, $amount);
            /*事务处理*/
            $insert = $this->get(SERVICE_WITHDRAW)->addReturn($userId, $amount, $realAmount, json_encode($userBank));
            $transactions = [
                [
                    'service' => SERVICE_WITHDRAW,
                    'action' => SQL_INSERT,
                    'insert' => $insert
                ]
            ];
            $serviceUserAccount->addAccount($userId, ACCOUNT_SUB, ACCOUNT_LOG_TYPE_WITHDRAW, $amount, '', [], $transactions);
            $this->sendSuccess();
        }
        else{
            $this->sendFail('API_LIMIT_ERROR');
            return false;
        }
    }

    /*
        /Api/Withdraw/getList
    */
    public function getListAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'device')){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $device = $data['device'];
        $serviceUser = $this->get(SERVICE_USER);
        $userId = $serviceUser->checkToken($data, $device);
        if(!$userId){
            $this->sendFail('TOKEN_ERROR');
            return false;
        }
        $page = (int)tryGet($data, 'page', 1);
        $limit = (int)tryGet($data, 'limit', 10);
        $temp = $this->getService()->getList($userId, $page, $limit);
        $list = $temp['list'];
        foreach($list as $k => $v){
            $v->type_text = getWithdrawTypeText($v->dry_type);
            $v->status_text = getWithdrawStatusText($v->dry_status);
            $v->dry_amount = bcadd($v->dry_amount, 0, 2);
            $list[$k] = $v;
        }
        $send = [
            'list' => $list
        ];
        $send = addPageInformation($send, $page, $limit, $temp['count']);
        $this->sendSuccess($send);
    }

    /*
        /Api/Withdraw/audit
    */
    public function auditAction()
    {
        $data = $this->getRequestData();
        if(notSetOrEmpty($data, 'id') || notSetOrEmpty($data, 'dry_status')){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $id = (int)$data['id'];
        $statusTo = (int)$data['dry_status'];
        $service = $this->getService();
        $withdraw = $service->one($id);
        if(empty($withdraw)){
            $this->sendFail('PARAMETER_ERROR', '', __LINE__);
            return false;
        }
        $statusFrom = $withdraw->dry_status;
        $map = [
            WITHDRAW_STATUS_APPLY . '_' . WITHDRAW_STATUS_AGREE  => ['note' => '待审核->已通过', 'return' => false],
            WITHDRAW_STATUS_APPLY . '_' . WITHDRAW_STATUS_REFUSE => ['note' => '待审核->已拒绝', 'return' => true],
            WITHDRAW_STATUS_AGREE . '_' . WITHDRAW_STATUS_REFUSE => ['note' => '已通过->已拒绝', 'return' => true],
            WITHDRAW_STATUS_AGREE . '_' . WITHDRAW_STATUS_PAY    => ['note' => '已通过->已打款', 'return' => false],
            WITHDRAW_STATUS_PAY   . '_' . WITHDRAW_STATUS_FINISH => ['note' => '已打款->已完成', 'return' => false]
        ];
        $key = "{$statusFrom}_{$statusTo}";
        if(!isset($map[$key])){
            $this->sendFail('FAIL', '非法操作', __LINE__);
            return false;
        }
        $return = $map[$key]['return'];
        $update = [
            'dry_status' => $statusTo
        ];
        /*不需要把金额返回*/
        if(!$return){
            $service->update($update, $id);
            $this->sendSuccess();
            return false;
        }
        $userId = $withdraw->dry_user;
        $amount = $withdraw->dry_amount;
        $serviceUserAccount = $this->get(SERVICE_USERACCOUNT);
        $transactions = [
            [
                'service' => SERVICE_WITHDRAW,
                'action' => SQL_UPDATE,
                'update' => $update,
                'updateId' => $id
            ]
        ];
        $serviceUserAccount->addAccount($userId, ACCOUNT_ADD, ACCOUNT_LOG_TYPE_WITHDRAW_RETURN, $amount, '提现拒绝并返款', [], $transactions);
        $this->sendSuccess();
    }

}